package com.cdream.basic.java8.io;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * @author cdream
 * @date 2022/8/15
 */
@Slf4j
public class SocketClient {
    private static final Integer PORT = 18080;
    private static final String HOST = "localhost";
    private static final String QUIT = "QUIT";

    public static void main(String[] args) {
        Socket socket = null;
        BufferedWriter bw = null;
        try {
            socket = new Socket(HOST, PORT);
            bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (true) {
                BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
                String consoleStr = console.readLine();
                if (QUIT.equals(consoleStr)) {
                    break;
                }
                bw.write(consoleStr+"\n");
                bw.flush();
                log.info("客户端发送：{}", consoleStr);

                String serverStr = br.readLine();
                log.info("客户端返回：{}", serverStr);

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                    System.out.println("关闭socket");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
